/**
 * service: division
 *
 * @author    Dmitry Ustimov
 * @date      March 2012
 *
 */
package com.gr

class DivisionService {

	static transactional = true
	
	def DistributorService
	
    def getlist() {
		return Division.list().collect{[
			text : it.title, 
			id   : ("Division_" + it.id)
		]}	
	}
	
	def getElement(params) {
		println(params)
		def el = Division.get(params.get("id"))
		return [
			'success' :'true', 
			id        : el.id, 
			title     : el.title, 
			email     : el.email, 
			startDate : el.startDate, 
			companyTo : el.companyTo.title]
	}
	
	def getlistAll() {
		return Division.list().collect{[
			text : it.title, 
			id   : it.title
		]}
	}
	
	def addElement(params) {
		println(params)
		def compTo = Company.get(params.get("companyTo"))
		if (compTo) {
			def newDiv = new Division()
			newDiv.title = params.get('title')
			newDiv.email = params.get('email')
			newDiv.startDate = new Date()
			newDiv.companyTo = compTo
			if (newDiv.save()) {
				return ['success':'true']
			}
			else {
				return ['success':'false']
			}
		}
		else {
			return ['success':'false']
		}
	}
	
	def editElement(params) {
		println(params)
		def compTo = Company.get(params.get("companyTo"))
		if (compTo) {
			def newDiv = Division.get(params.get('id'))
			newDiv.title = params.get('title')
			newDiv.email = params.get('email')
			if (params.get('startDate'))
				newDiv.startDate = new Date(params.get('startDate'))
			else
				newDiv.startDate = null
			newDiv.companyTo = compTo
			if (newDiv.save()) {
				return ['success':'true']
			}
			else {
				return ['success':'false']
			}
		}
		else {
			return ['success':'false']
		}
	}
	
	def deleteElement(params) {
		println(params)
		
		def foundDiv = Division.get(params.get("id"))
		def flist = Project.findAllByDivisionToLike(foundDiv)

		Iterator itr = flist.iterator()
		while(itr.hasNext()){
			def el = itr.next()

			def plist = Person.findAllByProjectToLike(el)

			Iterator itrp = plist.iterator()
			while(itrp.hasNext()){
				def elp = itrp.next()
				itrp.remove()
				elp.delete()
			}

			itr.remove()
			el.delete()
		}
		
		foundDiv.delete()
		
		return ['success':'true']	
	}
}
